<template>
  <div class="bg">
    <!-- 添加搜索框 -->
    <div class="ipt" style="margin-left: 20px; margin-top: 20px">
      <el-input
        v-model="search"
        placeholder="搜索菜单"
        style="width: 600px"
      ></el-input>
    </div>

    <div class="dishfather">
      <div
        class="dishproject"
        v-for="item in filteredState"
        :key="item.dish_id"
      >
        <div class="img1">
          <img :src="item.image_url" class="image" />
        </div>
        <div class="info">
          <p>菜品名：{{ item.dish_name }}</p>
          <p>价格：{{ item.price }}</p>
          <p>描述：{{ item.description }}</p>

          <!-- 份数 -->
          <el-input-number
            v-model="item.count"
            :min="0"
            :max="10"
            label="份数"
            @change="getCount"
          ></el-input-number>
        </div>
      </div>
    </div>

    <!-- 购物车图标 -->
    <div class="cart-btn">
      <el-button class="cart">
        <!-- 添加数字角标 -->
        <el-badge :value="shuzi" class="item"> </el-badge>
        <i class="iconfont">&#xe615;</i>
        <span>价格:{{ total }}元</span>
      </el-button>
      <el-button @click="confirmOrder">提交购物车</el-button>
      <el-button @click="cancelOrder">取消购物车</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect, computed } from "vue";
import { dishListApi, cartApi } from "@/utils/api";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();

const state = ref([]);
const shuzi = ref(0);
const total = ref(0);
const search = ref(""); // 添加搜索状态

// 获取路由参数
const { id } = route.params;

// 获取菜品详情
const getDishDetails = async () => {
  const res = await dishListApi({ id });
  console.log(res);
  if (res.code === 200) {
    state.value = res.data;
    state.value.forEach((item) => {
      item.image_url = `http://localhost:3000/images/${item.image_url}`;

      if (item.count === undefined) {
        item.count = 0;
      }
    });

    getCount();
    sum();
  } else {
    console.log("获取菜品详情失败");
  }
};

// 获取总份数
const getCount = () => {
  let count = 0;
  state.value.forEach((item) => {
    count += item.count;
  });
  shuzi.value = count;
};
//   获取总价格total
const sum = () => {
  let sum = 0;
  state.value.forEach((item) => {
    sum += item.count * item.price;
  });
  total.value = sum;
  // 保留两位小数
  total.value = total.value.toFixed(2);
};

// 提交订单
const confirmOrder = () => {
  if (shuzi.value === 0) {
    alert("请选择菜品");
    return;
  } else {
    const confirm = window.confirm("确认提交订单?");
    if (!confirm) return;

    // 获取用户信息
    const user = JSON.parse(localStorage.getItem("user"));
    // 获取菜品信息
    const dish = state.value;

    // 将user_id添加到dish中
    dish.forEach((item) => {
      item.user_id = user.user_id;
    });

    // 将数据存储到后端
    const cartData = cartApi({ user, dish });

    // 定时器 过2秒后跳转到订单页面
    const timer = setTimeout(() => {
      router.push({ path: "/home/cart" });
    }, 1000);
    // 销毁定时器
    timer.then(() => {
      clearTimeout(timer);
    });
  }
};

// 取消下单
const cancelOrder = () => {
  const confirm = window.confirm("确认取消订单?");
  if (confirm) {
    // 清空本地存储
    localStorage.removeItem("order");
    // 定时器 过2秒后跳转到首页
    const timer = setTimeout(() => {
      // 跳转到首页
      router.push({ path: "/home/rest" });
    }, 1000);

    // 在定时器执行后清除定时器
    timer.then(() => {
      clearTimeout(timer);
    });
  }
};

// 添加计算属性来过滤菜品
const filteredState = computed(() => {
  if (!search.value) return state.value;
  return state.value.filter((item) => item.dish_name.includes(search.value));
});

onMounted(() => {
  getDishDetails();
});

watchEffect(() => {
  getCount();
  sum();
});
</script>

<style lang="less" scoped>
.image {
  width: 150px;
  height: 150px;
}
.bg {
  display: flex;
  height: 100%;
  flex-direction: column;
  // justify-content: space-around;
  // height: 100vh;

  .ipt,
  .cart-btn {
    flex-shrink: 0;
  }
}
.dishfather {
  flex: 1;
  height: 0;
}
.dishproject {
  display: flex;
  margin-left: 20px;
  margin-top: 20px;
  .img1 {
    margin-right: 20px;
  }
  .info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-top: 20px;
    .el-input-number {
      margin-top: 10px;
    }
  }
}
.cart-btn {
  width: 400px;
  display: flex;
  justify-content: space-between;
  margin-left: 800px;
  .cart {
    display: flex;
    align-items: center;
  }
}
</style>
